package com.sh15tech.mp.weixin.listener;

import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.sh15tech.mp.weixin.thread.WxRemindThread;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.WebApplicationObjectSupport;

import com.sh15tech.mp.weixin.SysConfig;
import com.sh15tech.mp.weixin.thread.WxSynUserThread;
import com.sh15tech.mp.weixin.thread.WxTokenThread;


public class LaunchListener extends WebApplicationObjectSupport implements ServletContextListener {

	private Logger log = LogManager.getLogger(getClass());

    @Override
    public void contextInitialized(ServletContextEvent event) {
    	
    	loadSysConfig(event);
    	
    	// start token thread
    	new Thread(new WxTokenThread()).start();
    	log.info("thread started for get wx token !");
    	
    	// get jdbctemplate
    	ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());  
        JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");  
    	
        // start wx-reming thread
        new Thread(new WxRemindThread(jdbcTemplate)).start();
        log.info("thread started for wx remind !");
        
        // start user syn thread
//        new Thread(new WxSynUserThread(jdbcTemplate)).start();
    }

    private void loadSysConfig(ServletContextEvent event){
    	
    	Properties file = new Properties();
    	try {
			file.load(event.getServletContext().getResourceAsStream("WEB-INF/classes/config.properties"));
			
			for(String key : file.stringPropertyNames()){
				log.info(String.format("[properties]%s=%s",key,file.getProperty(key)));
	    		SysConfig.put(key, file.getProperty(key));
	    	}
		} catch (Exception e) {
			log.error("failed to load config file", e);
		}

    }
    
    @Override
    public void contextDestroyed(ServletContextEvent event) {
    	
    }
    
}
